package models

import "gorm.io/gorm"

type News struct {
	gorm.Model
	NewsTitle      string `gorm:"type:varchar(100)"`
	NewsTitleImage string `gorm:"type:text"`
	NewsData       string `gorm:"type:text"`
	NewsAuthorId   int    `gorm:"type:int"`
	NewsTypeId     int    `gorm:"type:int"`
	NewsStatus     string `gorm:"type:enum('已发布','已下架','待审核')"`
}
type Type struct {
	gorm.Model
	TypeName string `gorm:"type:varchar(30)"`
}

type FromListNews struct {
	UserName string `gorm:"type:varchar(30)"`
	News
	TypeName string `gorm:"type:varchar(30)"`
}

func (n *News) CreateNews() error {
	return DB.Create(&n).Error
}
func (n *News) GetNewsById() error {
	return DB.Where("id = ?", n.ID).Limit(1).Find(&n).Error
}
func (n *News) DelNewsById() error {
	return DB.Delete(&n).Error
}
func (n *News) GetNewsList(page int) (List []FromListNews, total int, err error) {
	const limit = 5
	err = DB.Model(&News{}).Joins("join types on types.id = news.news_type_id join users on news.news_author_id = users.id").Limit(limit).Offset((page - 1) * limit).Select("users.user_name,news.*,types.type_name").Scan(&List).Error
	if err != nil {
		return nil, 0, err
	}
	err = DB.Model(&News{}).Pluck("count(*)", &total).Error
	if err != nil {
		return nil, 0, err
	}
	return List, total, nil
}
func (n *News) GetNewsDataById() (Data FromListNews, err error) {
	err = DB.Model(&News{}).Joins("join types on types.id = news.news_type_id join users on news.news_author_id = users.id").Where("news.id = ?", n.ID).Limit(1).Select("users.user_name,news.*,types.type_name").Scan(&Data).Error
	if err != nil {
		return Data, err
	}

	return Data, nil
}
